// 建议的Service层设计

@Service
@Transactional
public class UserService {
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    /**
     * 用户注册业务逻辑
     */
    public void registerUser(SignupRequest signupRequest) {
        // 1. 验证用户名唯一性
        if (userRepository.existsByUsername(signupRequest.getUsername())) {
            throw new UserAlreadyExistsException("用户名已被使用");
        }
        
        // 2. 验证邮箱唯一性
        if (userRepository.existsByEmail(signupRequest.getEmail())) {
            throw new EmailAlreadyExistsException("邮箱已被使用");
        }
        
        // 3. 创建用户
        User user = new User(
            signupRequest.getUsername(),
            signupRequest.getEmail(),
            passwordEncoder.encode(signupRequest.getPassword())
        );
        
        // 4. 保存用户
        userRepository.save(user);
        
        // 5. 可以添加其他业务逻辑
        // - 发送欢迎邮件
        // - 记录注册日志
        // - 初始化用户配置等
    }
    
    /**
     * 根据用户名查找用户
     */
    public Optional<User> findByUsername(String username) {
        return userRepository.findByUsername(username);
    }
    
    /**
     * 检查用户是否存在
     */
    public boolean userExists(String username) {
        return userRepository.existsByUsername(username);
    }
}

@Service
public class AuthService {
    
    @Autowired
    private AuthenticationManager authenticationManager;
    
    @Autowired
    private JwtUtils jwtUtils;
    
    @Autowired
    private UserService userService;
    
    /**
     * 用户认证业务逻辑
     */
    public JwtResponse authenticateUser(LoginRequest loginRequest) {
        // 1. 执行认证
        Authentication authentication = authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken(
                loginRequest.getUsername(), 
                loginRequest.getPassword()
            )
        );
        
        // 2. 设置安全上下文
        SecurityContextHolder.getContext().setAuthentication(authentication);
        
        // 3. 生成JWT令牌
        String jwt = jwtUtils.generateJwtToken(authentication);
        
        // 4. 获取用户详情
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        
        // 5. 可以添加其他业务逻辑
        // - 记录登录日志
        // - 更新最后登录时间
        // - 检查账户状态等
        
        return new JwtResponse(jwt,
            userDetails.getId(),
            userDetails.getUsername(),
            userDetails.getEmail());
    }
}

// 重构后的Controller
@RestController
@RequestMapping("/api/auth")
public class AuthController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private AuthService authService;
    
    @PostMapping("/signin")
    public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
        try {
            JwtResponse response = authService.authenticateUser(loginRequest);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(new MessageResponse("登录失败: " + e.getMessage()));
        }
    }
    
    @PostMapping("/signup")
    public ResponseEntity<?> registerUser(@Valid @RequestBody SignupRequest signUpRequest) {
        try {
            userService.registerUser(signUpRequest);
            return ResponseEntity.ok(new MessageResponse("用户注册成功!"));
        } catch (UserAlreadyExistsException | EmailAlreadyExistsException e) {
            return ResponseEntity.badRequest()
                .body(new MessageResponse("注册失败: " + e.getMessage()));
        }
    }
}